package com.st.valid.jsr3.simple.exceptionHandle;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Priority;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @创建人: 放生
 * @创建时间: 2022/4/7
 * @描述:
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.st.valid.jsr3.simple.controller")//管理的controller(这个包下的controller都会被管理)
public class ValidExceptionControllerAdvice {

    @ExceptionHandler(value = Exception.class) // 也可以返回ModelAndView
    public Map<String,String> handleValidException(MethodArgumentNotValidException exception){
        Map<String,String> map=new HashMap<>();
        // 获取数据校验的错误结果
        BindingResult bindingResult = exception.getBindingResult();
        //获取当前的国际化语言,
        ResourceBundle message = ResourceBundle.getBundle("messages", Locale.US);
        // 处理错误
        bindingResult.getFieldErrors().forEach(fieldError -> {
//            String message = fieldError.getDefaultMessage();
            String field = fieldError.getField();
            map.put(field,message.getString(field));
        });
        log.error("数据校验出现问题{},异常类型{}",exception.getMessage(),exception.getClass());

        return map;
    }


}
